package com.image;

import java.util.HashMap;

public class LeetCode2 {

	public boolean containsDuplicate(int[] nums) {
		HashMap map = new HashMap();
		for (int i = 0; i < nums.length; i++) {
			if (map.containsKey(nums[i])) {
				return true;
			}
			map.put(nums[i], 0);
		}
		return false;
	}
	//7,6,4,3,1

	public int maxProfit(int[] prices) {
		int buy = 0;
		int sell = 0;
		int next;
		int now;
		int length = prices.length;
		boolean wantBuy = true;
		int profit;
		int sum = 0;

		if (length == 0 || length == 1) {
			return 0; // 异常情况
		}
		next = prices[0];
		for (int i = 0; i < length - 1; i++) { // 从第二个价格开始
			now = next;
			next = prices[i + 1];
			if (wantBuy == true) {
				if (now < next) {
					buy = now;
					wantBuy = false;
				}
			} else {
				if (now > next) {
					sell = now;
					profit = sell - buy;
					sum = sum + profit;
					wantBuy = true;
					// System.out.println("buy="+buy+" sell="+sell+"
					// profit="+profit);
				}
			}
		}
		if (wantBuy == false) {
			sell = next;
			profit = sell - buy;
			sum = sum + profit;
			wantBuy = true;
			// System.out.println("buy="+buy+" sell="+sell+" profit="+profit);
		}

		return sum;

	}


	public static void main(String[] args) {
		int[][] testTable = {{7,1,5,3,6,4},{1,2,3,4,5},{7,6,4,3,1},{1,6,2,7}};
		for (int[] ito : testTable) {
			test(ito);
		}
	}
	private static void test(int[] ito) {
		LeetCode2 solution = new LeetCode2();
		int rtn;
		long begin = System.currentTimeMillis();
		for (int i = 0; i < ito.length; i++) {
		    System.out.print(ito[i]+" ");		    
		}
		System.out.println();
		//开始时打印数组
		
		rtn = solution.maxProfit(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		//System.out.println(ito + ": rtn=" + rtn);
		System.out.println(ito + ": rtn=" +rtn);
//		for (int i = 0; i < ito.length; i++) {
//		    System.out.print(ito[i]+" ");
//		}//打印结果几数组
		
		System.out.println();
		System.out.println("耗时：" + (end - begin) + "ms");
		System.out.println("-------------------");
	}
 

}
